package com.pason.onlineshop.mainshop.functionaltest.framework;

import org.mortbay.jetty.Server;
import org.mortbay.jetty.webapp.WebAppContext;

public class WebServer {
	public static final int DEV_SERVER_PORT = 8080;

	public static void main(final String[] args) throws Exception {
		System.setProperty("application.environment", "dev_");
		System.out.println(System.getProperty("java.class.path"));
		new WebServer(DEV_SERVER_PORT).stopAtShutdown().setupHandlers()
				.start();
	}

	private Server server;

	public WebServer(final int port) {
		server = new Server(port);
	}

	/**
	 * Please note that we need to add the classpath again if we are running
	 * this from maven because jetty does not seem to understand there are tld
	 * files otherwise.
	 * handler.setExtraClasspath(System.getProperty("java.class.path"));
	 * 
	 * @return
	 * @throws Exception
	 */
	public WebServer start() throws Exception {
		server.start();
		return this;
	}

	public void stop() {
		try {
			server.stop();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private WebServer setupHandlers() {
		WebAppContext contextHandler = new WebAppContext("src/main/webapp", "/shop");
		contextHandler.setParentLoaderPriority(true);
		server.addHandler(contextHandler);
		return this;
	}

	private WebServer stopAtShutdown() {
		server.setStopAtShutdown(true);
		return this;
	}

}
